package com.demo.springBootDemo05.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class User {
	private Integer id;
	private String username;
	private String password;
	private static final List<User> USERS = Collections.synchronizedList(new ArrayList<User>());
	static {
		User user1 = new User(1, "admin", "admin");
		USERS.add(user1);
		User user2 = new User(2, "user", "user");
		USERS.add(user2);
	}
	private static final AtomicInteger idGen = new AtomicInteger(USERS.size());

	public static final User addUser(String username, String password) {
		User user = new User(username, password);
		USERS.add(user);
		return user;
	}

	public static final User updateUser(Integer id, String username, String password) {
		User user = getUser(id);
		User oldUser = new User(id, user.getUsername(), user.getPassword());
		if (user != null) {
			user.setUsername(username);
			user.setPassword(password);
		}
		return oldUser;
	}

	public static final User deleteUser(Integer id) {
		User user = getUser(id);
		USERS.remove(user);
		return user;
	}

	public static final User getUser(Integer id) {
		if (id != null && USERS.size() > 0) {
			for (User user : USERS) {
				if (user.getId().equals(id)) {
					return user;
				}
			}
		}
		return null;
	}

	public static final List<User> listUser() {
		return USERS;
	}

	public User() {
		super();
	}

	public User(Integer id, String username, String password) {
		this();
		this.id = id;
		this.username = username;
		this.password = password;
	}

	public User(String username, String password) {
		this(idGen.incrementAndGet(), username, password);
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
